package com.hh.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hh.admin.entity.SysMenu;
import com.hh.admin.mapper.SysMenuMapper;
import com.hh.admin.service.ISysMenuService;
import com.hh.core.entity.ZtreeEntity;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hxn
 * @since 2018-01-16
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
		implements ISysMenuService {

	@Autowired
	SysMenuMapper sysMenuMapper;

	@Override
	public List<SysMenu> getMenuNavByRoleid(Set<Long> roleList) {
		List<SysMenu> menuList = sysMenuMapper.getMenuList(roleList);
		List<SysMenu> menuNavList = new ArrayList<>();
		Long parenId = 0L;
		for(SysMenu menu:menuList){
			if(parenId == menu.getParentId()){      //第一级菜单
				menuNavList.add(menu);
			}
		}
		for(SysMenu menu:menuNavList){
			getChlidMenu(menuList,menu);      //获取除第一级菜单的所有子菜单
		}
		return menuNavList;
	}

	/**
	 * 
	* @Title: getChlidMenu  
	* @Description:   获取子菜单节点
	* @param @param menuList
	* @param @param menu
	* @param @return    设定文件  
	* @return List<SysMenu>    返回类型  
	* @author hxn
	* @date 2018年1月25日 上午10:25:14  
	* @throws
	 */
	private List<SysMenu> getChlidMenu(List<SysMenu> menuList,SysMenu menu){
		List<SysMenu> chlidMenu = new ArrayList<>();
		for(SysMenu sMenu:menuList){
			if(menu.getId() == sMenu.getParentId()){   
				menu.setChildMenu(getChlidMenu(menuList,sMenu));        //存在子菜单,获取子节点
			}
		}
		for(SysMenu sMenu:menuList){
			if(menu.getParentId() == sMenu.getParentId()){
				chlidMenu.add(sMenu);
			}
		}
		return chlidMenu;
	}

	@Override
	public String getSelectMenuData() {
		List<SysMenu> menuList = sysMenuMapper.getMenuList();
		Integer level = 1;
		List<SysMenu> list = new ArrayList<>();
		StringBuffer sb = new StringBuffer();
		JSONObject json = new JSONObject();
		while(true){
			for(SysMenu menu:menuList){
				if(level == menu.getLevel()){
					list.add(menu);
				}
			}
			if(list.size()>0){
				json.put("title", "层级"+level);
				json.put("list", list);
				sb.append(json.toJSONString()+",");
				level ++ ;
				list = new ArrayList<>();
			}else{
				break;
			}
		}
		if(sb.length()>0){
			return "["+sb.substring(0, sb.length()-1)+"]";
		}
		return "";
	}

	@Override
	public List<ZtreeEntity> getZtree() {
		return sysMenuMapper.getMenuTreeByRoleId(null);
	}
	
	
}
